using System;
using System.Collections.Generic;
using System.Text;
using System.Web;
using Microsoft.SharePoint;

namespace ARF.Web
{
    public enum CacheScope
    {
        User,
        Page,
        Web,
        Site,
        Undefined
    }

    public class ArfCache
    {
        public string KeySuffix = "";
        public string SiteKey = null;
        public string Key = "";
        public int Timeout = 2;

        public ArfCache(string sCacheKey) { Key = sCacheKey; }

        private Nullable<CacheScope> _scopeHint = null;
        private Nullable<bool> _enabledHint = null;

        public bool IsCached
        {
            get
            {
                // Don't cache for Admins!!
                if (SPContext.Current.Web.UserIsWebAdmin) return false;

                return (HttpContext.Current.Cache[CacheKey] != null);
            }
        }

        public object Value
        {
            get
            {
                return HttpContext.Current.Cache[CacheKey];
            }

            set
            {
                HttpContext.Current.Cache.Add(CacheKey, value, null, DateTime.Now.AddMinutes(Timeout), System.Web.Caching.Cache.NoSlidingExpiration, System.Web.Caching.CacheItemPriority.Normal, null);
            }
        }

        protected string CacheKey
        {
            get
            {
                if (!string.IsNullOrEmpty(SiteKey)) return SiteKey;

                string sKey = Key + "({0})" + KeySuffix;

                return string.Format(sKey, ScopeKey()); 
            }
        }

        protected string ScopeKey()
        {
            if (Scope == CacheScope.User) return HttpContext.Current.Request.Url.PathAndQuery + HttpContext.Current.User.Identity.Name;

            if (Scope == CacheScope.Web) return SPContext.Current.Web.Url;

            if (Scope == CacheScope.Site) return SPContext.Current.Site.Url;

            if (Scope == CacheScope.Page) return HttpContext.Current.Request.Url.PathAndQuery;

            //Undefined
            return "";
        }

        public CacheScope Scope
        {
            get 
            {
                if (_scopeHint != null) return (CacheScope)_scopeHint;

                return CacheScope.Undefined;
            }
            set 
            {
                _scopeHint = value;
            }
        }

        public bool Enabled
        {
            get
            {
                if (_enabledHint != null) return (bool)_enabledHint;

                return false;
            }

            set
            {
                _enabledHint = value;
            }
        }

    }
}
